using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

[System.Serializable]
public class SaveItemData
{
    public string name;
    public bool isPassed;

    public SaveItemData(string name, bool isPassed)
    {
        this.name = name;
        this.isPassed = isPassed;
    }
}

public class LoadAndSave : MonoBehaviour
{
    [Header("存档物品")] 
    /*[SerializeField] private List<ItemSO> itemList;
    [SerializeField] private AlbumSO album;*/
    [Header("存档文件名")] 
    [SerializeField] private string itemSaveFileName = "ItemSave";
    [SerializeField] private string albumSaveFileName = "LevelSave";
    
    private string itemSavePath;
    private string albumSavePath;
    
    public Dictionary<string, SaveItemData> saveData = new Dictionary<string, SaveItemData>();
    public List<bool> levelPassed = new List<bool>();
    public bool start = false; // AlbumSO中的start属性
    public bool end = false;   // AlbumSO中的end属性

    private static LoadAndSave instance;
    public static LoadAndSave Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<LoadAndSave>();
                if (instance == null)
                {
                    GameObject obj = new GameObject("LoadAndSave");
                    instance = obj.AddComponent<LoadAndSave>();
                    DontDestroyOnLoad(obj);
                }
            }
            return instance;
        }
    }

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
            InitializeSaveSystem(); // 确保路径初始化
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    private void InitializeSaveSystem()
    {
        // 确保文件名不为空
        if (string.IsNullOrEmpty(itemSaveFileName))
        {
            Debug.LogError("Item save file name is not set!");
            return;
        }
        if (string.IsNullOrEmpty(albumSaveFileName))
        {
            Debug.LogError("Album save file name is not set!");
            return;
        }

        itemSavePath = Path.Combine(Application.persistentDataPath, itemSaveFileName);
        albumSavePath = Path.Combine(Application.persistentDataPath, albumSaveFileName);
    
        // 确保目录存在
        Directory.CreateDirectory(Path.GetDirectoryName(itemSavePath));
        Directory.CreateDirectory(Path.GetDirectoryName(albumSavePath));
    
        Debug.Log($"Item save path: {itemSavePath}");
        Debug.Log($"Album save path: {albumSavePath}");
    
        // 启动加载协程
        StartCoroutine(FullLoad());
    }

    // ================= 文件操作 =================
    private void LoadFromFile()
    { 
        saveData.Clear();
        
        if (File.Exists(itemSavePath))
        {
            foreach (string line in File.ReadAllLines(itemSavePath))
            {
                if (string.IsNullOrWhiteSpace(line)) continue;
                
                string[] parts = line.Split(',');
                if (parts.Length < 2) continue;

                string name = parts[0].Trim();
                bool isPassed = parts[1].Trim() == "1";
                
                saveData[name] = new SaveItemData(name, isPassed);
                
                Debug.Log($"Load From File: {name} , {isPassed}");
            }
            Debug.Log($"物品存档加载: {saveData.Count} 条记录");
        }
        else
        {
            Debug.LogWarning("ItemFile not found, is Creating a new one? 创建初始物品文件");
            CreateInitialItemFile();
        }

        levelPassed.Clear();
        start = false; // 初始化 AlbumSO 的 start 属性
        end = false;   // 初始化 AlbumSO 的 end 属性
        
        if (File.Exists(albumSavePath))
        {
            List<string> lines = File.ReadAllLines(albumSavePath).Where(line => !string.IsNullOrWhiteSpace(line)).ToList();

            if (lines.Count >= 1)
            {
                start = lines[0].Trim() == "1"; // 加载 start 属性
            }

            if (lines.Count >= 2)
            {
                end = lines[1].Trim() == "1";   // 加载 end 属性
            }

            if (lines.Count >= 3)
            {
                levelPassed = lines.Skip(2).Select(line => line.Trim() == "1").ToList();
                Debug.Log($"关卡存档加载: {levelPassed.Count} 条记录");
            }
            else
            {
                Debug.LogWarning("AlbumFile format incorrect or incomplete, is Creating a initial one? 创建初始专辑文件");
                CreateInitialAlbumFile();
            }
        }
        else
        {
            Debug.LogWarning("AlbumFile not found, is Creating a new one? 创建初始专辑文件");
            CreateInitialAlbumFile();
        }
    }

    private void CreateInitialItemFile()
    {
        /*saveData = itemList.ToDictionary(
            item => item.name,
            item => new SaveItemData(item.name, false)
        );
        */
        
        SaveItemFile();
    }
    
    private void CreateInitialAlbumFile()
    {
        /*start = album.start; // 从 AlbumSO 初始化 start
        end = album.end;     // 从 AlbumSO 初始化 end
        levelPassed = album.levelState.ToList();
        */

        SaveAlbumFile();
    }
    
    private void SaveItemFile()
    {
        if (string.IsNullOrEmpty(itemSavePath))
        {
            Debug.LogError("Item save path is not initialized!");
            return;
        }

        List<string> lines = saveData.Values
            .Select(state => $"{state.name},{(state.isPassed ? "1" : "0")}").ToList();
    
        Debug.Log($"Saving item data to: {itemSavePath}");
        File.WriteAllLines(itemSavePath, lines);
    }

    private void SaveAlbumFile()
    {
        if (string.IsNullOrEmpty(albumSavePath))
        {
            Debug.LogError("Album save path is not initialized!");
            return;
        }

        List<string> lines = new List<string>();
        lines.Add(start ? "1" : "0"); // 保存 start 属性
        lines.Add(end ? "1" : "0");   // 保存 end 属性
        lines.AddRange(levelPassed.Select(state => state ? "1" : "0")); // 保存关卡状态
    
        Debug.Log($"Saving album data to: {albumSavePath}");
        File.WriteAllLines(albumSavePath, lines);
    }
    
    // ================= 内存操作 =================
    private void LoadItemsToSO()
    {
        /*foreach (ItemSO item in itemList)
        {
            if (saveData.TryGetValue(item.name, out SaveItemData state))
            {
                item.isPassed = state.isPassed;
                Debug.Log($"Load items to SO: Name: {item.name} ,isPassed: {item.isPassed}");
            }
            else
            {
                saveData[item.name] = new SaveItemData(item.name, item.isPassed);
                Debug.Log($"create saveData : Name: {item.name}, isPassed: {item.isPassed}");
            }
        }*/
    }
    
    private void SaveItemsFromSO()
    {
        /*foreach (ItemSO item in itemList)
        {
            if (saveData.ContainsKey(item.name))
            {
                saveData[item.name].isPassed = item.isPassed;
                Debug.Log($"Save items from SO: Name: {item.name}, isPassed: {item.isPassed}");
            }
            else
            {
                saveData[item.name] = new SaveItemData(item.name, item.isPassed);
                Debug.Log($"create saveData : Name: {item.name}, isPassed: {item.isPassed}");
            }
        }*/
    }
    
    private void LoadAlbumToSO()
    {
        /*// 更新 AlbumSO 的 start 和 end 属性
        album.start = start;
        album.end = end;

        // 确保长度一致
        while (levelPassed.Count < album.levelState.Count)
        {
            levelPassed.Add(false);
        }
        
        for (int i = 0; i < album.levelState.Count; i++)
        {
            if (i < levelPassed.Count)
            {
                album.levelState[i] = levelPassed[i];
            }
        }*/
    }
    
    private void SaveAlbumFromSO()
    {
        /*// 更新 start 和 end
        start = album.start;
        end = album.end;

        // 确保长度一致
        while (levelPassed.Count < album.levelState.Count)
        {
            levelPassed.Add(false);
        }
        
        for (int i = 0; i < album.levelState.Count; i++)
        {
            if (i < levelPassed.Count)
            {
                levelPassed[i] = album.levelState[i];
            }
        }*/
    }
    
    // ================= 公共接口 =================
    public IEnumerator FullLoad()
    {
        LoadFromFile();
        LoadItemsToSO();
        LoadAlbumToSO();
        yield return null;
    }

    public IEnumerator FullSave()
    {
        SaveItemsFromSO();
        SaveAlbumFromSO();
        SaveItemFile();
        SaveAlbumFile();
        yield return null;
    }
}